package org.oak.service.impl;

import org.oak.model.User;
import org.oak.repository.UserRepository;
import org.oak.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * org.oak.service.impl.UserServiceImpl
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/29 18:38
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    /**
     * 将查询结果缓存
     */
    @Cacheable(value = "user", key = "#id")
    public User getUserById(Long id) {
        System.out.println("从数据库查询用户信息，id: " + id);
        return userRepository.findById(id).orElse(null);
    }

    /**
     * 更新缓存
     */
    @CachePut(value = "user", key = "#user.id")
    public User updateUser(User user) {
        System.out.println("更新用户信息，id: " + user.getId());
        return userRepository.save(user);
    }

    /**
     * 删除缓存
     */
    @CacheEvict(value = "user", key = "#id")
    public void deleteUser(Long id) {
        System.out.println("删除用户信息，id: " + id);
        userRepository.deleteById(id);
    }

    /**
     * 清除所有缓存
     */
    @CacheEvict(value = "user", allEntries = true)
    public void clearCache() {
        System.out.println("清除所有用户缓存");
    }
}
